package com.tj.common.util.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Properties;
import java.util.Random;
import java.util.Set;

public class CommonTestUtil {
    public static HashMap<String, String> loadValueMapFromClassPathFile(Class clazz, String fileName, String encoding) throws Exception {
        InputStream ins = clazz.getClassLoader().getResourceAsStream(fileName);

        if (ins == null) {
            throw new IOException("Can not find file under classpath :" + fileName);
        }
        try {
            return loadValueMapFromReader(new InputStreamReader(ins, encoding));
        } finally {
            ins.close();
        }
    }

    public static HashMap<String, String> loadValueMapFromReader(Reader ins) throws Exception {
        HashMap<String, String> map = new HashMap<String, String>();
        Properties p = new Properties();
        p.load(ins);
        Set keys = p.keySet();
        for (Object key : keys) {
            map.put((String) key, (String) p.getProperty((String) key));
        }
        try {
            return map;
        } finally {
            ins.close();
        }
    }

    static Random random = new Random();

    public static double randomDouble() {
        return random.nextDouble();
    }

    public static int nextInt(int range) {
        return random.nextInt(range);
    }

    private static long lastNumber = 1000000;

    public static String getNonRepeatString() {
        synchronized (CommonTestUtil.class) {
            lastNumber++;
            return "s" + lastNumber;
        }
    }

    private static String[] encoding = new String[] { "GBK", "ISO-8859-1", "UTF-8" };

    public static void tryEncoding(String s) {
        for (int i = 0; i < encoding.length; i++) {
            String a = encoding[i];
            for (int j = 0; j < encoding.length; j++) {
                String b = encoding[j];
                try {
                    System.out.println(a + ":" + b + "=" + new String(s.getBytes(a), b));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
